/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import entity.Contact;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.FacebookApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import properties.PropertyHolder;

/**
 *
 * @author dzaric
 */
public class ImportFromFacebook extends HttpServlet {

	private static final String NETWORK_NAME = "Facebook";
	private static final String PROTECTED_RESOURCE_URL = "https://graph.facebook.com/me/friends";
	private static final Token EMPTY_TOKEN = null;

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			if (request.getParameter("code") == null) {
				String clientId = "116924128386873";
				String apiKey = "116924128386873";
				String apiSecret = "dfd97b196200b58b98680024864a3075";
				OAuthService service = new ServiceBuilder().provider(FacebookApi.class).apiKey(apiKey).apiSecret(apiSecret).callback("http://localhost:8080/EvIn/ImportFromFacebook").build();
				String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);

				request.getSession().setAttribute("facebook_api_service", service);
				response.sendRedirect(authorizationUrl);
			} else {
				OAuthService service=(OAuthService)(request.getSession().getAttribute("facebook_api_service"));
				String authorization_code=request.getParameter("code");
				
				Verifier verifier = new Verifier(authorization_code);
				System.out.println();

				// Trade the Request Token and Verfier for the Access Token
				System.out.println("Trading the Request Token for an Access Token...");
				Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
				System.out.println("Got the Access Token!");
				System.out.println("(if your curious it looks like this: " + accessToken + " )");
				System.out.println();

				// Now let's go and ask for a protected resource!
				System.out.println("Now we're going to access a protected resource...");
				OAuthRequest oauth_request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
				service.signRequest(accessToken, oauth_request);
				Response oauth_response = oauth_request.send();
				System.out.println("Got it! Lets see what we found...");
				System.out.println();
				System.out.println(oauth_response.getCode());
				System.out.println(oauth_response.getBody());

				List<Contact> facebookContacts=new ArrayList<Contact>();
				
				try {
					JSONObject json_resp = new JSONObject(oauth_response.getBody());
					JSONArray seq = new JSONArray(json_resp.get("data").toString());
					for (int i = 0; i < seq.length(); i++) {
						String[] name=(((JSONObject) seq.get(i)).get("name")).toString().split(" ");
						String[] f_name=new String[2];
						f_name[0]=name[0];
						if(name.length>1){
							f_name[1]=name[1];
						}else{
							f_name[1]="N/A";
						}
						Contact newContact=new Contact();
						newContact.setFirstName(f_name[0]);
						newContact.setLastName(f_name[1]);
						facebookContacts.add(newContact);
					}


					request.getSession().setAttribute("facebook_contacts", facebookContacts);
					response.sendRedirect("/EvIn/user/facebookimport.faces");

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}

	// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	/**
	 * Handles the HTTP <code>GET</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
